/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;


import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.scene.bean.ItemListBean;
import com.koron.scene.mapper.GoodsListMapper;
import com.koron.scene.service.api.GoodsListService;
import com.koron.scene.utils.BaseEntityUtil;
import com.koron.scene.utils.BusinessCode;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.swan.bean.MessageBean;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("deprecation")
@Service
public class GoodsListServiceImpl implements GoodsListService {

    private static final Logger logger = LoggerFactory.getLogger(GoodsListServiceImpl.class);
    @Override
    public MessageBean queryForList(String corpCode, String itemName,
                                    String itemType, String itemSpecification,
                                    Integer page, Integer pageSize) {
        MessageBean<DataBean<ItemListBean>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            GoodsListMapper mapper = factory.getMapper(GoodsListMapper.class);
            // 查询
            Map map = new HashMap();
            map.put("corpCode", corpCode);
            map.put("itemName", itemName);
            map.put("itemType", itemType);
            map.put("itemSpecification", itemSpecification);
            if (page == null || pageSize == null){
                map.put("pageStart", null);
                map.put("pageStop", null);
            }else {
                page = (page == null || page < 1) ? 1 : page;
                pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;
                int pageStart = (page - 1) * pageSize;
                map.put("pageStart", pageStart);
                map.put("pageStop", pageSize);
            }
            List<ItemListBean> list = mapper.queryForList(map);
            DataBean<ItemListBean> dataBean = new DataBean<>();
            dataBean.setList(list);
            if (page != null && pageSize != null){
                dataBean.setPageSize(pageSize);
                dataBean.setPageNo(page);
                // 总条数
                Integer totalNumber = mapper.countForList(map);
                int num = totalNumber / pageSize;
                // 总页数
                Integer totalPage = totalNumber % pageSize == 0 ? num : num + 1;
                dataBean.setTotalNumber(totalNumber);
                dataBean.setTotalPage(totalPage);
            }
            msg.setData(dataBean);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription(BusinessCode.SUCCESS.getDescription());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean queryById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        try (SessionFactory factory = new SessionFactory()) {
            GoodsListMapper mapper = factory.getMapper(GoodsListMapper.class);
            ItemListBean bean = mapper.queryById(id);
            if (bean == null) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("没有查询到该物品！");
            }
            msg.setData(bean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean deleteById(String id) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), void.class);
        if (StringUtils.isEmpty(id)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            GoodsListMapper mapper = factory.getMapper(GoodsListMapper.class);
            int count = mapper.countApplyItemsByItemListId(id);
            if (count > 0) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("该物品存在领用信息记录，不允许删除!");
                factory.close(false);
                return msg;
            }
            int i = mapper.deleteById(id);
            if (i != 1) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("删除失败!");
                factory.close(false);
                return msg;
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean insert(StaffBean user, ItemListBean bean) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "新增成功", void.class);
        // 参数校验
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(bean.getCorpCode()) || StringUtils.isEmpty(bean.getCorpName())
                || StringUtils.isEmpty(bean.getItemName()) || StringUtils.isEmpty(bean.getItemType())
                || StringUtils.isEmpty(bean.getItemTypeName()) || StringUtils.isEmpty(bean.getItemSpecification())) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            GoodsListMapper mapper = factory.getMapper(GoodsListMapper.class);
            // 判断 物品是否已经存在:根据物品名称，物品类型，物品规格 判断
            if (mapper.queryBeanByVerify(
                    bean.getCorpCode(), bean.getItemName(),
                    bean.getItemType(), bean.getItemSpecification(), null) != null) {
                factory.close(false);
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("该物品信息已经存在!");
                return msg;
            }
            bean.setResidualQuantity(0);
            BaseEntityUtil.setAddBaseProperties(bean, user);
            mapper.insert(bean);
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean update(StaffBean user, ItemListBean bean) {
        MessageBean msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "修改成功", void.class);
        // 参数校验
        if (user == null) {
            msg.setCode(BusinessCode.NO_LOGIN.getCode());
            msg.setDescription(BusinessCode.NO_LOGIN.getDescription());
            return msg;
        }
        if (StringUtils.isEmpty(bean.getItemName()) || StringUtils.isEmpty(bean.getItemType())
                || StringUtils.isEmpty(bean.getItemTypeName()) || StringUtils.isEmpty(bean.getItemSpecification())) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        SessionFactory factory = new SessionFactory();
        try {
            GoodsListMapper mapper = factory.getMapper(GoodsListMapper.class);
            // 判断 物品是否已经存在:根据物品名称，物品类型，物品规格 判断
            if (mapper.queryBeanByVerify(
                    bean.getCorpCode(), bean.getItemName(),
                    bean.getItemType(), bean.getItemSpecification(), bean.getId()) != null) {
                factory.close(false);
                msg.setCode(BusinessCode.EXCEPTION.getCode());
                msg.setDescription("该物品信息已经存在!");
                return msg;
            }
            bean.setUpdateUser(user.getCode());
            bean.setUpdateUserName(user.getName());
            bean.setUpdateTime(new Date());
            if (mapper.update(bean) != 1) {
                factory.close(false);
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("修改失败");
            }
            factory.close();
        } catch (Exception e) {
            factory.close(false);
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
        }
        return msg;
    }
}
